package com.health.tools;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

	/**
	 * 计算两个日期之间相差的天数
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差天数
	 * @throws ParseException
	 * 
	 */
	public static int daysBetween(Date smdate, Date bdate)
			throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		smdate = sdf.parse(sdf.format(smdate));
		bdate = sdf.parse(sdf.format(bdate));
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

	/**
	 * 字符串的日期格式的计算
	 * 
	 * @throws ParseException
	 */
	public static int daysBetween(String smdate, String bdate)
			throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.setTime(sdf.parse(smdate));
		long time1 = cal.getTimeInMillis();
		cal.setTime(sdf.parse(bdate));
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}
	
	public static int getAge(Date birthday) {
		int days;
		try {
			days = DateUtil.daysBetween(birthday, new Date());
			int year = days/365;
			return year;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 计算两个日期之间 相差的月数
	 * @param birthday
	 * @return
	 * @author 王婷婷
	 * @date 2017年3月22日 上午10:30:03
	 */
	public static int getMonthsByDate(Date curDate,Date birthday) {
	    int months=-1;
	  
	    try{
	    	int result = curDate.getMonth() -birthday.getMonth();
		    int month = (curDate.getYear() -birthday.getYear()) * 12;
		    System.out.println(Math.abs(month + result));   
		    months=Math.abs(month + result);
	    }catch(Exception e){
	    	e.printStackTrace();
	    }
	    
		return months;
	}
	/**
	 * 获取两个日期之间的 月份差
	 * @param aftertime 大时间
	 * @param pretime 小时间
	 * @return
	 * @author 王婷婷
	 * @date 2017年3月22日 上午10:36:03
	 */
	public static int getMonthsByString(String aftertime,String pretime) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
//	    String str1 = "2012-02";
//	    String str2 = "2011-01";
	    Calendar bef = Calendar.getInstance();
	    Calendar aft = Calendar.getInstance();
	    
	    try {
	    	bef.setTime(sdf.parse(pretime));
			aft.setTime(sdf.parse(aftertime));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
	    int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
	    System.out.println(Math.abs(month + result));   
		return 0;
	}
	
}
